using Lzfy_His_Service.Models;
using Lzfy_His_Service.Repositories;

namespace Lzfy_His_Service.Services
{
    public class CallLogService : ICallLogService
    {
        private readonly ICallLogRepository _callLogRepository;
        private readonly ILogger<CallLogService> _logger;

        public CallLogService(ICallLogRepository callLogRepository, ILogger<CallLogService> logger)
        {
            _callLogRepository = callLogRepository;
            _logger = logger;
        }

        public async Task<CallLog?> GetByIdAsync(int id)
        {
            if (id <= 0)
            {
                throw new ArgumentException("ID必须大于0", nameof(id));
            }

            return await _callLogRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CallLog>> GetAllAsync()
        {
            return await _callLogRepository.GetAllAsync();
        }

        public async Task<IEnumerable<CallLog>> GetByUsernameAsync(string username)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentException("用户名不能为空", nameof(username));
            }

            return await _callLogRepository.GetByUsernameAsync(username);
        }

        public async Task<IEnumerable<CallLog>> GetByCallPhoneAsync(string callPhone)
        {
            if (string.IsNullOrWhiteSpace(callPhone))
            {
                throw new ArgumentException("呼叫电话不能为空", nameof(callPhone));
            }

            return await _callLogRepository.GetByCallPhoneAsync(callPhone);
        }

        public async Task<IEnumerable<CallLog>> GetRecentAsync(int minutes = 60)
        {
            if (minutes <= 0)
            {
                throw new ArgumentException("时间范围必须大于0", nameof(minutes));
            }

            return await _callLogRepository.GetRecentAsync(minutes);
        }

        public async Task<CallLogQueryResponse> GetPagedAsync(
            int pageIndex = 1,
            int pageSize = 20,
            string? username = null,
            string? callPhone = null,
            DateTime? startDate = null,
            DateTime? endDate = null)
        {
            if (pageIndex <= 0)
            {
                throw new ArgumentException("页码必须大于0", nameof(pageIndex));
            }

            if (pageSize <= 0 || pageSize > 100)
            {
                throw new ArgumentException("页大小必须在1-100之间", nameof(pageSize));
            }

            if (startDate.HasValue && endDate.HasValue && startDate > endDate)
            {
                throw new ArgumentException("开始日期不能大于结束日期");
            }

            var (data, totalCount) = await _callLogRepository.GetPagedAsync(
                pageIndex, pageSize, username, callPhone, startDate, endDate);

            return new CallLogQueryResponse
            {
                Items = data.ToList(),
                TotalCount = totalCount,
                PageIndex = pageIndex,
                PageSize = pageSize
            };
        }

        public async Task<int> CreateAsync(CallLogCreateRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrWhiteSpace(request.Username))
            {
                throw new ArgumentException("用户名不能为空", nameof(request.Username));
            }

            if (string.IsNullOrWhiteSpace(request.Fullname))
            {
                throw new ArgumentException("姓名不能为空", nameof(request.Fullname));
            }

            if (string.IsNullOrWhiteSpace(request.CallPhone))
            {
                throw new ArgumentException("呼叫电话不能为空", nameof(request.CallPhone));
            }

            var callLog = new CallLog
            {
                Username = request.Username,
                Fullname = request.Fullname,
                CallPhone = request.CallPhone,
                UserPhone = request.UserPhone,
                SendMsg = request.SendMsg
            };

            var id = await _callLogRepository.CreateAsync(callLog);
            _logger.LogInformation("创建通话记录成功，ID: {Id}, 用户: {Username}", id, request.Username);
            return id;
        }

        public async Task<bool> UpdateAsync(int id, CallLogUpdateRequest request)
        {
            if (id <= 0)
            {
                throw new ArgumentException("ID必须大于0", nameof(id));
            }

            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            // 检查记录是否存在
            var existingCallLog = await _callLogRepository.GetByIdAsync(id);
            if (existingCallLog == null)
            {
                return false;
            }

            if (string.IsNullOrWhiteSpace(request.Username))
            {
                throw new ArgumentException("用户名不能为空", nameof(request.Username));
            }

            if (string.IsNullOrWhiteSpace(request.Fullname))
            {
                throw new ArgumentException("姓名不能为空", nameof(request.Fullname));
            }

            if (string.IsNullOrWhiteSpace(request.CallPhone))
            {
                throw new ArgumentException("呼叫电话不能为空", nameof(request.CallPhone));
            }

            var callLog = new CallLog
            {
                Id = id,
                Username = request.Username,
                Fullname = request.Fullname,
                CallPhone = request.CallPhone,
                UserPhone = request.UserPhone,
                SendMsg = request.SendMsg,
                InputDate = existingCallLog.InputDate // 保持原有的创建时间
            };

            var result = await _callLogRepository.UpdateAsync(callLog);
            if (result)
            {
                _logger.LogInformation("更新通话记录成功，ID: {Id}, 用户: {Username}", id, request.Username);
            }
            return result;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            if (id <= 0)
            {
                throw new ArgumentException("ID必须大于0", nameof(id));
            }

            // 检查记录是否存在
            var existingCallLog = await _callLogRepository.GetByIdAsync(id);
            if (existingCallLog == null)
            {
                return false;
            }

            var result = await _callLogRepository.DeleteAsync(id);
            if (result)
            {
                _logger.LogInformation("删除通话记录成功，ID: {Id}", id);
            }
            return result;
        }
    }
}
